using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;


namespace MyUnityUtils
{
    public class UnityTimeUtils
    {
    
        /// <summary>
        /// calculate time difference of [t1 - t2]
        /// </summary>
        /// <returns>timeDifference</returns>
        public static TimeSpan CalculateTimeDifference(string t_1, string t_2, string time_format="yyyy-MM-dd HH:mm:ss")
        {
            DateTime tNow = DateTime.ParseExact(t_1, time_format, System.Globalization.CultureInfo.InvariantCulture);
            DateTime guoQiShiJian = DateTime.ParseExact(t_2, time_format, System.Globalization.CultureInfo.InvariantCulture);

            TimeSpan timeDifference = guoQiShiJian - tNow;

            return timeDifference;
        }
    
        public static string FormatDuration(int seconds, int length = 2, string join_separator="")
        {
            var intervals = new List<(string name, int count)>
            {
                ("年", 60 * 60 * 24 * 365),
                ("月", 60 * 60 * 24 * 30),
                ("周", 60 * 60 * 24 * 7),
                ("天", 60 * 60 * 24),
                ("小时", 60 * 60),
                ("分", 60),
                ("秒", 1)
            };

            var result = new List<string>();

            foreach (var interval in intervals)
            {
                int value = seconds / interval.count;
                if (value > 0)
                {
                    seconds -= value * interval.count;
                    result.Add(value + interval.name);
                }
            }

            if (length > 0)
            {
                result = result.GetRange(0, length);
            }
            
            string res = result.Count > 0 ? string.Join(join_separator, result) : $"{seconds}秒";
            return res;
        }
        
        public static void Main()
        {
            string tNowStr = "2024-05-22 15:41:43";
            string guoQiShiJianStr = "2024-05-23 00:00:00";
            
            var result = CalculateTimeDifference(tNowStr, guoQiShiJianStr);
            
            Debug.Log("时间差: " + result);
            Debug.Log("以秒为单位的时间差: " + result.TotalSeconds + "秒");
            Debug.Log("格式化后的字符时间: " + FormatDuration(BdPackage.BdUtils.conv_to_int(result.TotalSeconds)));
        }
    }
}
